package com.white.controller;

import com.white.bean.SignIn;
import com.white.mapper.SignInMapper;
import com.white.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 签到控制器
 * 1.签到
 * 2.获取最大连续签到次数
 * 3.获取累计签到次数
 */
@RestController
public class SignInController {
    @Autowired
    SignInMapper signInMapper;

    @GetMapping("/signIn")
    public int block(@CookieValue(UserController.LOGIN_USER_ID) long userId) {
        try {
            signInMapper.create(userId);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @GetMapping("/signInInformation")
    public Object signInInformation(@CookieValue(UserController.LOGIN_USER_ID) long userId) {
        HashMap<String, Object> ans = new HashMap<>();
        List<SignIn> signIns = signInMapper.searchByUserId(userId);
        int maxContinuous = 1, curMContinuous = 1;
        for (int i = signIns.size() - 1; i > 0; i--) {
            if (Utils.isNextDay(signIns.get(i).getCreateTime(), signIns.get(i - 1).getCreateTime())) {
                curMContinuous++;
            } else {
                curMContinuous = 1;
            }
            maxContinuous = Integer.max(curMContinuous, maxContinuous);
        }
        String latestDate = signIns.get(0).getCreateTime().split(" ")[0];
        Date date = new Date();
        ans.put("count", signIns.size());
        ans.put("maxContinuous", maxContinuous);
        ans.put("isSignIn", latestDate.equals(Utils.dateToString(date)));
        return ans;
    }
}
